<template>
  <div class="app-container">
    <!--查询  -->
    <el-row>
      <el-input style="width:200px" v-model="tableQuery.orgName" placeholder="机构名称"></el-input>
      <span style="margin-right: 15px"></span>
      <el-tooltip class="item" content="搜索" placement="top" >
        <el-button icon="el-icon-search" circle @click="fetchData()" v-perm="'b:org:query'"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate" v-perm="'b:org:add'">{{textMap.create}}</el-button>
    <el-button type="primary" icon="el-icon-tickets" class="export-excel" size="mini" @click="handleExport" v-perm="'b:org:excel'">导出</el-button>

    <div style="margin-bottom: 30px"></div>
    <!--列表-->
    <el-table style="width: 100%"
              :data="tableData"
              v-loading.body="tableLoading"
              element-loading-text="加载中"
              border fit highlight-current-row>
      <el-table-column prop="id" label="机构id"></el-table-column>
      <el-table-column prop="orgName" label="机构名称"></el-table-column>
      <el-table-column prop="code" label="机构代码"></el-table-column>
      <el-table-column prop="areaCode" label="行政区划代码"></el-table-column>
      <el-table-column prop="address" label="详细地址"></el-table-column>
      <el-table-column prop="notifyUrl" label="支付回调地址"></el-table-column>
      <el-table-column prop="dataUrl" label="对账数据地址"></el-table-column>
      <el-table-column prop="remark" label="备注信息"></el-table-column>
      <el-table-column prop="sortNo" label="排序"></el-table-column>
      <el-table-column label="操作">
        <dataFormlate slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button @click="handleUpdate(scope.$index,scope.row)" size="medium" type="info" icon="el-icon-edit" circle plain v-perm="'b:org:edit'"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button @click="handleDelete(scope.$index,scope.row)" size="medium" type="danger" icon="el-icon-delete" circle plain v-perm="'b:org:delete'"></el-button>
          </el-tooltip>
        </dataFormlate>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <!--弹出窗口：新增/编辑机构-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="机构名称"  label-width="110px" prop="orgName">
          <el-input v-model="dataForm.orgName"></el-input>
        </el-form-item>

        <el-form-item label="机构代码" label-width="110px" prop="code">
          <el-input v-model="dataForm.code"></el-input>
        </el-form-item>

        <el-form-item label="行政区划代码" label-width="110px" prop="areaCode">
          <el-input v-model="dataForm.areaCode"></el-input>
        </el-form-item>
        <el-form-item label="详情地址" label-width="110px" prop="address">
          <el-input v-model="dataForm.address"></el-input>
        </el-form-item>
        <el-form-item label="支付回调地址" label-width="110px" prop="notifyUrl">
          <el-input v-model="dataForm.notifyUrl"></el-input>
        </el-form-item>
        <el-form-item label="对账数据地址" label-width="110px" prop="dataUrl">
          <el-input v-model="dataForm.dataUrl"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="110px" prop="remark">
          <el-input v-model="dataForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="排序" label-width="110px" prop="sortNo">
          <el-input-number v-model="dataForm.sortNo"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>>

<script>

import orgApi from '@/api/org'
import debounce from 'lodash/debounce'
import { resetTemp } from '@/utils'
import { confirm, pageParamNames } from '@/utils/constants'

export default {

  name: 'orgManage',
  data() {
    const validateName = (rule, value, callback) => {
      if (this.dialogStatus === 'create' && value === '') {
        callback(new Error('必填'))
      } else {
        callback()
      }
    }
    return {
      tableLoading: false,
      tableData: [],
      tableQuery: {
        orgName: null
      },
      tablePage: {
        current: null,
        pages: null,
        size: null,
        total: null
      },
      dialogFormVisible: false,
      editRolesDialogVisible: false,
      dialogStatus: '',
      dataForm: {
        idx: null, // tableData中的下标
        id: null,
        orgName: null,
        code: null,
        areaCode: null,
        address: null,
        notifyUrl: null,
        dataUrl: null,
        remark: null,
        sortNo: null
      },
      textMap: {
        update: '编辑机构',
        create: '新增机构'
      },
      rules: {
        orgName: [{ validator: validateName, trigger: 'blur' }],
        notifyUrl: [
          { required: true, message: '支付回调地址不能为空', trigger: 'blur' }
        ],
        dataUrl: [
          { required: true, message: '对账数据地址', trigger: 'blur' }
        ]
      },
      checkAll: false,
      isIndeterminate: true
    }
  },

  created() {
    this.initData()
  },

  watch: {
    // 延时查询
    'tableQuery.orgName': debounce(function() {
      this.fetchData()
    }, 500)
  },
  // watch
  methods: {

    initData() {
      this.fetchData()
    },

    // 分页
    handleSizeChange(val) {
      this.tablePage.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.tablePage.current = val
      this.fetchData()
    },

    // 查询
    fetchData(current) {
      if (current) {
        this.tablePage.current = current
      }
      this.tableLoading = true
      orgApi.queryOrganization(this.tableQuery, this.tablePage).then(res => {
        this.tableData = res.data.page.records
        console.log(this.tableData)
        this.tableLoading = false
        pageParamNames.forEach(name => this.$set(this.tablePage, name, res.data.page[name]))
      })
    },
    // 导出
    handleExport() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['机构ID', '机构代码', '机构名称', '行政区划代码', '详情地址', '支付回调地址', '对账数据地址', '备注信息', '排序']
        const filterVal = ['id', 'code', 'orgName', 'areaCode', 'notifyUrl', 'dataUrl', 'address', 'remark', 'sortNo']

        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '系统机构',
          autoWidth: true
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    // 更新
    handleUpdate(idx, row) {
      this.dataForm = Object.assign({}, row) // copy obj
      this.dataForm.idx = idx
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        const dataFormData = Object.assign({}, this.dataForm)// copy obj
        orgApi.updateOrganization(dataFormData).then(res => {
          dataFormData.updated = res.data.updated
          this.tableData.splice(dataFormData.idx, 1, dataFormData)
          this.dialogFormVisible = false
          this.$message.success('更新成功')
        })
      })
    },
    // 删除
    handleDelete(idx, row) {
      this.$confirm('您确定要删除该机构？', '提示', confirm).then(() => {
        orgApi.delSysOrganization({ id: row.id }).then(res => {
          this.tableData.splice(idx, 1)
          --this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 新增
    handleCreate() {
      this.dialogStatus = 'create'
      resetTemp(this.dataForm)
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      this.dataForm.sortNo = this.tableData.length + 1
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        orgApi.addSysOrganization(this.dataForm).then((res) => {
          this.dataForm.id = res.data.id// 后台传回来新增记录的id
          this.tableData.unshift(Object.assign({}, this.dataForm))
          ++this.tablePage.total
          this.dialogFormVisible = false
          this.$message.success('添加成功')
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.role-checkbox {
  margin-left: 0px;
  margin-right: 15px;
}
.export-excel {
  margin-left: 500rpx;
}
</style>
